<?php

/**
 * Plugin to initialize application state
 *
 * @uses       Zend_Controller_Plugin_Abstract
 * @version    $Id: $
 */
class WSB_Controller_Plugin_Navigation extends Zend_Controller_Plugin_Abstract
{

	private $_xml;
	private $_acl;

    /**
     * @param  Zend_Controller_Request_Abstract $request
     * @return void
     */
    public function postDispatch(Zend_Controller_Request_Abstract $request)
    {
		$auth = WSB_Auth_Backend::getInstance();
		if($auth->hasIdentity()) {
			$beuser = $auth->getIdentity();
			$this->_acl = $beuser->getAcl();
		}
		$filepathToXML = sprintf(WSB_APP_PATH . 'i18n/sitemap.%s.xml', Cms_Model_DbTable_Language::getAdminLanguage());
		$this->_xml = simplexml_load_file($filepathToXML);
		$this->getResponse()->append('navigation', $this->_render());
    }

    /**
     * @return string
     */
	private function _render()
	{
		$html = '<ul>';
		// Frontend-Link
		$html .= '<li><a target="_blank" href="../">Frontend</a></li>';
		foreach($this->_xml->children() AS $firstLevel) {
		    $aro = $this->_buildAro($firstLevel);
			if($this->_isAllowed($aro)) {
				$html .= '<li>';
				$html .= $this->_buildUrl($firstLevel);
			}
			if(count($firstLevel->children()) > 0) {
				$html .= '<ul>';
				foreach($firstLevel AS $secondLevel) {
				    $aro = $this->_buildAro($secondLevel);
					if($this->_isAllowed($aro)) {
						$html .= sprintf('<li>%s</li>', $this->_buildUrl($secondLevel));
					}
				}
				$html .= '</ul>';
			}
			$aro = $this->_buildAro($firstLevel);
			if($this->_isAllowed($aro)) {
				$html .= '</li>';
			}
		}
		$html .= '</ul>';
		return $html;
	}

	/**
	 * @param array $attributes
	 * @return string
	 */
	private function _buildUrl($attributes)
	{
	    $module = isset($attributes['module']) ? $attributes['module'] : null;
	    $controller = isset($attributes['controller']) ? $attributes['controller'] : 'index';
	    $action = isset($attributes['action']) ? $attributes['action'] : 'index';
	    $globals = array();
	    if(isset($attributes['globals'])) {
	        $pairs = WSB_Div::csvToArray($attributes['globals'], '&');
	        foreach($pairs AS $pair) {
	            $kv = WSB_Div::csvToArray($pair, '=');
                $globals[$kv[0]] = isset($kv[1]) ? $kv[1] : null;
	        }
	    }
		$url = WSB_Controller_Url::getUrl($controller, $action, array(), $module, $globals);
		return WSB_Controller_Url::getHtmlLink($attributes['label'], $url);
	}

	/**
	 * @param string $aro
	 * @return boolean
	 */
	private function _isAllowed($aro)
	{

		if(!$this->_acl instanceof Zend_Acl) {
			return false;
		}

		$parts = WSB_Div::csvToArray($aro, '.');
		$module 	= isset($parts[0]) ? $parts[0] : 'index';
		$controller = isset($parts[1]) ? $parts[1] : 'index';
		$action 	= isset($parts[2]) ? $parts[2] : 'index';

		// ---->
		// @todo: Die nachfolgenden Codezeilen entsprechen exakt dem Code in
		// WSB_Controller_Plugin_Permission::preDispatch();
        $hasAccess = false;
    	if($this->_acl->isAllowed(WSB_ACL_ROLE_ADMIN)) {
    		$hasAccess = true;
    	} else {
        	/* Wildcard access
				Alle moeglichen Kombinationen sind:
				*
				*.*
				page.*
				*.*.*
				*.*.index
				*.index.*
				*.index.index
				page.*.*
				page.*.index
				page.index.*
				page.index.index
        	*/
        	$_aros = array(
        		// 1-stellig
        		"*",
        		// 2-stellig
        		"$module.*",
        		"*.*",
        		// 3-stellig
        		"*.*.*",
        		"*.*.".$action,
        		"*.$controller.*",
        		"*.$controller.$action",
        		"$module.*.*",
        		"$module.*.$action",
        		"$module.$controller.*",
        		"$module.$controller.$action"
        	);

        	// Access
        	foreach($_aros AS $_aro) {
        		if($this->_acl->isAllowed(WSB_ACL_ROLE_STAFF, 'DEFAULT', $_aro)) {
        			$hasAccess = true;
        			break;
        		}
        	}

        	// Deny
        	foreach($_aros AS $_aro) {
        		if($this->_acl->getRuleType($_aro, WSB_ACL_ROLE_STAFF, 'DEFAULT') == Zend_Acl::TYPE_DENY) {
        			if(!$this->_acl->isAllowed(WSB_ACL_ROLE_STAFF, 'DEFAULT', $_aro)) {
        				$hasAccess = false;
        				break;
        			}
        		}
        	}

    	}
    	// Bis hier...
    	// <----
    	return $hasAccess;
	}

	/**
	 * @param array $attributes
	 * @return string
	 */
	private function _buildAro($attributes)
	{
	    $aro = '';
	    $delim = '';
	    if(isset($attributes['module'])) {
	        $aro .= $attributes['module'];
	        $delim = '.';
	    }
	    if(isset($attributes['controller'])) {
	        $aro .= $delim.$attributes['controller'];
	        $delim = '.';
	    }
	    if(isset($attributes['action'])) {
	        $aro .= $delim.$attributes['action'];
	    }
	    return $aro;
	}

}